package com.songlanyun.common.config;


import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.swing.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 信号量 工具类
 */
@Component
public class SemaphoreTool {


    @Resource
    private RedissonClient redissonClient;

    /**
     * 获取信号量对象
     * @param key
     * @return
     */
    public RSemaphore getRSemaphore(String key){
        return redissonClient.getSemaphore(key);
    }


    /**
     * 设置信号量的值
     * @param key
     * @param size
     * @return
     */
    public Boolean setRSemaphorePermits(String key,Integer size)
    {
        RSemaphore semaphore = this.getRSemaphore(key);
        return semaphore.trySetPermits(size);
    }


    /**
     * 尝试获得信号量
     */
    public boolean tryAcquire(String key, int size) {
        RSemaphore semaphore = this.getRSemaphore(key);
        return semaphore.tryAcquire(size);
    }

    /**
     * 释放信号量
     */
    public void release(String key, int size) {
        RSemaphore semaphore = this.getRSemaphore(key);
        semaphore.release(size);//释放信号量
    }

    /**
     * 信号量的permits数
     * 获取当前信号量的剩余数量
     */
    public  Integer permitsNum(String key) {
        RSemaphore semaphore = this.getRSemaphore(key);
        return semaphore.availablePermits();
    }

    /**
     * 清空permits
     *
     */
    public Integer drainPermits(String key) {
        RSemaphore semaphore = this.getRSemaphore(key);
        return semaphore.drainPermits();
    }



}
